﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KorkolaskuriBL
{
    public class EqualTotalPayment : IPaymentStrategy
    {
        public EqualTotalPayment()
        {
        }

        public string Name
        {
            get { return Resources.Strings.EqualTotalPaymentName; }
        }

        public IEnumerable<LoanPayment> CalculatePayments(
            double initialBalance, double interestRate, int interestPeriods, int paymentPeriods, double periodicPayment)
        {
            double balance = initialBalance;
            double periodicIntrest = interestRate / interestPeriods;
            double principalPortion;
            double interestPortion;

            for (int i = 0; i < paymentPeriods; i++) {
                interestPortion = balance * periodicIntrest;
                principalPortion = periodicPayment - interestPortion;
                if (principalPortion < balance)
                    balance -= principalPortion;
                else
                    balance -= balance;
                yield return new LoanPayment(
                    i + 1,
                    principalPortion,
                    interestPortion,
                    balance);
            }
        }

        public double CalculatePeriodicPayment(
            double initialBalance, double interestRate, int interestPeriods, int paymentPeriods)
        {
            double K = initialBalance;
            double q = interestRate / interestPeriods;
            double n = paymentPeriods;

            return (q * K) / (1 - Math.Pow((1 + q), -n));
        }

        public int CalculatePaymentPeriods(
            double initialBalance, double interestRate, int interestPeriods, double periodicPayment)
        {
            double K = initialBalance;
            double A = periodicPayment;
            double q = interestRate / interestPeriods;

            return (int)Math.Ceiling(Math.Log(A / (A - K * q), Math.E) / Math.Log(q + 1, Math.E));
        }
    }
}
